---
import DefaultLayout from '@layouts/DefaultLayout.astro'
import PageHeader from '@components/PageHeader.astro'
import { Card, Pagination } from 'accessible-astro-components'
import type { PaginateFunction, Page } from 'astro'

// Import images directly for optimization
import postImage1 from '@assets/images/posts/post-image-1.png'
import postImage2 from '@assets/images/posts/post-image-2.png'
import postImage3 from '@assets/images/posts/post-image-3.png'
import postImage4 from '@assets/images/posts/post-image-4.png'
import postImage5 from '@assets/images/posts/post-image-5.png'
import postImage6 from '../../assets/images/posts/post-image-6.png'

interface Post {
  id: number
  userId: number
  title: string
  body: string
  featuredImage: any
  shortUrl: string
}

export async function getStaticPaths({ paginate }: { paginate: PaginateFunction }) {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts')
  const data = await response.json()

  const postImages = [postImage1, postImage2, postImage3, postImage4, postImage5, postImage6]

  function truncateTitle(title: string) {
    const words = title.split(' ')
    const truncated = words.slice(0, 4).join(' ')
    return truncated
  }

  const postsWithImages = data.slice(0, 30).map((post: any) => {
    const truncatedTitle = truncateTitle(post.title)
    return {
      ...post,
      featuredImage: postImages[post.id % postImages.length],
      title: truncatedTitle,
      shortUrl: truncatedTitle.replaceAll(' ', '-').toLowerCase(),
    }
  })

  return paginate(postsWithImages, { pageSize: 6 })
}

interface Props {
  page: Page<Post>
}

const { page } = Astro.props as Props
---

<DefaultLayout
  title="Blog"
  description="An example of a blog with dynamic content fetched from JSONPlaceholder using the title, body and userId."
>
  <PageHeader
    title="Blog"
    subtitle='An example of a blog with dynamic content fetched from <a href="https://jsonplaceholder.typicode.com/posts">JSONPlaceholder</a> using the title, body and userId. The Accessible Astro Card Component is used here to display al the posts.'
    bgType="bordered"
  />

  <section class="my-12">
    <div class="container">
      <p class="text-sm"><em>Post {page.start + 1} through {page.end + 1} of {page.total} total posts</em></p>
      <ul class="my-3 grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
        {
          page.data.map((post) => (
            <li>
              <Card
                imageComponent={post.featuredImage}
                url={'/blog/' + post.shortUrl}
                title={post.title}
                headingLevel="h2"
                footer={'userId:' + post.userId}
                fullHeight={true}
              >
                {post.body}
              </Card>
            </li>
          ))
        }
      </ul>
      {
        page && page.lastPage > 1 && (
          <div class="mt-12 grid place-content-center">
            <Pagination
              firstPage={page.url.prev ? '/blog' : null}
              previousPage={page.url.prev ? page.url.prev : null}
              nextPage={page.url.next ? page.url.next : null}
              lastPage={page.url.next ? `/blog/${page.lastPage}` : null}
              currentPage={`${page.currentPage}`}
              totalPages={`${page.lastPage}`}
              ariaLabel="Blog pagination"
            />
          </div>
        )
      }
    </div>
  </section>
</DefaultLayout>
